package com.vote.mvc.taglib;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.TagSupport;


public class Pager extends TagSupport {

    private static final long serialVersionUID = -268373073040339762L;

    private int curpage = 0;
    private boolean showNumber = true;
    private boolean showHeadTail = true;
    private String url = "";
    private int count = 0;
    private int itemPerPage = 10;
    
    @Override
    public int doStartTag() throws JspException{
        try
        {
            JspWriter out = pageContext.getOut();
            String head = "";
            String tail = "";
            String number = "";
            String per = "";
            String next = "";
            if(itemPerPage < count){
                int pages = count / itemPerPage + (count % itemPerPage == 0 ? 0 : 1);
                if(showHeadTail){
                    if(curpage != 0){
                        head = "<a href=\""+url+"curpage=0\">首页</a>";
                    }
                    if(curpage != pages){
                        tail = "<a href=\""+url+"curpage="+pages+"\">尾页</a>";
                    }
                }
                if(curpage > 0){
                    per = "<a href=\""+url+"curpage="+(curpage - 1)+"\">上一页</a>";
                }
                if(curpage < pages){
                    next = "<a href=\""+url+"curpage="+(curpage + 1)+"\">下一页</a>";
                }
                if(showNumber){
                    int start = (curpage-2) < 0 ? 0 : (curpage - 2);
                    int end = (curpage+2) > pages ? pages : (curpage+2);
                    for(int i = start; i <= end; i++){
                        if(i == curpage){
                            number += "<b>"+(i+1)+"</b>";
                        }
                        else{
                            number += "<a href=\""+url+"curpage="+i+"\">"+(i+1)+"</a>";
                        }
                    }
                }
                out.write(head+per+number+next+tail);
            }
        }
        catch (Exception e)
        {
            throw new JspException(e);
        }
        return EVAL_PAGE;
    }
    
    public void setCurpage(int curpage) {
        this.curpage = curpage;
    }

    public void setShowNumber(boolean showNumber) {
        this.showNumber = showNumber;
    }

    public void setShowHeadTail(boolean showHeadTail) {
        this.showHeadTail = showHeadTail;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    public void setCount(int count) {
        this.count = count;
    }

    public void setItemPerPage(int itemPerPage) {
        this.itemPerPage = itemPerPage;
    }
}
